<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <title>OAuth2登录集成</title>
    <style>
        /* 原有样式保持不变 */
        .container {
            width: 300px;
            margin: 100px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
        }
        .form-group input {
            width: 284px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .submit-btn {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-bottom: 15px;
        }
        .submit-btn:hover {
            background-color: #0056b3;
        }
        .oauth-buttons {
            margin-top: 20px;
            text-align: center;
        }
        .oauth-btn {
            display: inline-block;
            padding: 8px 15px;
            margin: 0 5px;
            border-radius: 4px;
            color: white;
            text-decoration: none;
            cursor: pointer;
        }
        .divider {
            margin: 20px 0;
            text-align: center;
            position: relative;
            font-size: 14px;
        }
        .divider:before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #ddd;
        }
        .divider span {
            background: white;
            padding: 0 10px;
            position: relative;
            color: #666;
        }
        .login-text {
            font-size: 12px;
            color: #000;
        }
        .form-container {
            display: none;
        }
        .form-container.active {
            display: block;
        }
        .form-switch {
            text-align: center;
            font-size: 14px;
            margin-top: 10px;
        }
        .form-switch a {
            color: #007bff;
            text-decoration: none;
            cursor: pointer;
        }
        .form-switch a:hover {
            text-decoration: underline;
        }
        .error-message {
            color: #dc3545;
            margin-top: 10px;
            text-align: center;
            display: none;
        }

        /* 新增微信弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            border-radius: 8px;
            width: 340px;
            text-align: center;
        }

        .modal-header {
            margin-bottom: 15px;
        }

        .modal-header h3 {
            margin: 0;
            color: #333;
        }

        .close {
            float: right;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
        }

        #wechatQrcode {
            width: 300px;
            height: 300px;
            margin: 0 auto;
            border: 1px solid #eee;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .qrcode-tip {
            margin-top: 15px;
            color: #666;
            font-size: 14px;
        }

        .refresh-btn {
            margin-top: 15px;
            padding: 8px 15px;
            background-color: #07C160;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .refresh-btn:hover {
            background-color: #06AD56;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 登录表单 -->
    <div id="loginForm" class="form-container active">
        <h2 style="text-align: center; margin-bottom: 20px;">OAuth2登录集成</h2>
        <form action="/auth/perform_login" method="post">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" autocomplete="off"  name="username" required/>
            </div>
            <div class="form-group">
                <label>密码：</label>
                <input type="password" name="password" required/>
            </div>
            <button type="submit" class="submit-btn">登录</button>
        </form>
        <div class="form-switch">
            <a onclick="switchForm('register')">没有账号？立即注册</a>
        </div>
    </div>

    <!-- 注册表单 -->
    <div id="registerForm" class="form-container">
        <h2 style="text-align: center; margin-bottom: 20px;">注册</h2>
        <form id="registerFormElement">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" name="username" required/>
            </div>
            <div class="form-group">
                <label>密码：</label>
                <input type="password" name="password" required/>
            </div>
            <div class="form-group">
                <label>昵称：</label>
                <input type="text" name="nickname"/>
            </div>
            <div class="form-group">
                <label>邮箱：</label>
                <input type="email" name="email"/>
            </div>
            <button type="submit" class="submit-btn">注册</button>
        </form>
        <div class="form-switch">
            <a onclick="switchForm('login')">已有账号？立即登录</a>
        </div>
    </div>

    <div id="errorMessage" class="error-message"></div>

    <div class="divider">
        <span>或使用以下方式登录</span>
    </div>

    <div class="oauth-buttons">
        <a href="/auth/oauth2/authorization/github" class="oauth-btn" title="GitHub登录">
            <img src="http://localhost:8000/images/github.png" width="20px" height="20px"/>
            <div class="login-text">GitHub登录</div>
        </a>
        <a href="https://gitee.com/oauth/authorize?client_id=48e236ced1b9c2c4a076f3f0a76cbae009131ad28d18821cf94feb0feef0a42a&redirect_uri=http://ea68fa65.natappfree.cc/giteeCallback&response_type=code&state=1" class="oauth-btn">
            <img src="http://localhost:8000/images/gitee.png" width="20px" height="20px"/>
            <div class="login-text">Gitee登录</div>
        </a>
        <!-- 修改微信登录按钮，阻止默认跳转行为 -->
        <a href="javascript:void(0)" onclick="showWechatModal()" class="oauth-btn">
            <img src="http://localhost:8000/images/weChat.png" width="20px" height="20px"/>
            <div class="login-text">微信登录</div>
        </a>

    </div>
</div>

<!-- 修改微信弹窗部分 -->
<div id="wechatModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <span class="close" onclick="closeModal()">&times;</span>
            <h3>微信扫码登录</h3>
        </div>
        <div id="wechatQrcode">
            <!-- 二维码将在这里显示 -->
            <p>正在加载二维码...</p>
        </div>
        <p class="qrcode-tip">请使用微信扫描二维码登录</p>
        <button class="refresh-btn" onclick="refreshQrcode()">刷新二维码</button>
    </div>
</div>

<script>
    function switchForm(form) {
        document.getElementById('loginForm').classList.toggle('active');
        document.getElementById('registerForm').classList.toggle('active');
        document.getElementById('errorMessage').style.display = 'none';
    }

    document.getElementById('registerFormElement').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = {
            username: formData.get('username'),
            password: formData.get('password'),
            nickname: formData.get('nickname'),
            email: formData.get('email')
        };

        fetch('/auth/user/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(data => {
                if (data.message) {
                    // 注册成功，切换到登录表单
                    switchForm('login');
                    document.getElementById('errorMessage').style.display = 'none';
                } else {
                    // 显示错误信息
                    document.getElementById('errorMessage').textContent = data;
                    document.getElementById('errorMessage').style.display = 'block';
                }
            })
            .catch(error => {
                document.getElementById('errorMessage').textContent = '注册失败，请稍后重试';
                document.getElementById('errorMessage').style.display = 'block';
            });
    });

    // 微信登录相关功能
    let qrcodeTimer = null;
    let currentSceneId = null;

    // 显示微信登录弹窗
    function showWechatModal() {
        const modal = document.getElementById('wechatModal');
        modal.style.display = 'block';
        loadWechatQrcode();
    }

    // 关闭弹窗
    function closeModal() {
        const modal = document.getElementById('wechatModal');
        modal.style.display = 'none';
        clearInterval(qrcodeTimer);
        currentSceneId = null;
    }

    // 刷新二维码
    function refreshQrcode() {
        loadWechatQrcode();
    }

    // 加载微信二维码
    function loadWechatQrcode() {
        const qrcodeContainer = document.getElementById('wechatQrcode');
        qrcodeContainer.innerHTML = '<p>正在加载二维码...</p>';

        // 清除之前的定时器
        if (qrcodeTimer) {
            clearInterval(qrcodeTimer);
        }

        // 调用后端接口获取二维码
        fetch('/wxLogin')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.qrcodeUrl && data.sceneId) {
                    qrcodeContainer.innerHTML = `<img src="${data.qrcodeUrl}" alt="微信二维码" style="width:300px;height:300px;">`;
                    currentSceneId = data.sceneId;

                    // 开始轮询检查登录状态（每3秒检查一次）
                    qrcodeTimer = setInterval(checkLoginStatus, 3000);
                } else {
                    qrcodeContainer.innerHTML = '<p>获取二维码失败，请重试</p>';
                }
            })
            .catch(error => {
                qrcodeContainer.innerHTML = '<p>获取二维码失败，请刷新页面</p>';
                console.error('获取二维码失败:', error);
            });
    }

    // 检查登录状态
    function checkLoginStatus() {
        if (!currentSceneId) return;

        fetch(`/wxCheck?sceneId=${currentSceneId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'scanned') {
                    // 用户已扫码
                    document.querySelector('.qrcode-tip').textContent = '扫码成功，请在手机上确认登录';
                } else if (data.status === 'confirmed') {
                    // 登录成功
                    clearInterval(qrcodeTimer);
                    closeModal();
                    window.location.href = '/'; // 跳转到首页或用户中心
                } else if (data.status === 'expired') {
                    // 二维码过期
                    document.querySelector('.qrcode-tip').textContent = '二维码已过期，请刷新';
                    clearInterval(qrcodeTimer);
                }
            })
            .catch(error => {
                console.error('检查登录状态失败:', error);
            });
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('wechatModal');
        if (event.target == modal) {
            closeModal();
        }
    }
</script>
</body>
</html>